package com.lyloou;

import com.lyloou.handler.UserServiceHandler;
import com.lyloou.server.JSONSerializer;
import com.lyloou.server.RpcDecoder;
import com.lyloou.server.RpcRequest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.InputStream;
import java.util.Properties;

@SpringBootApplication
public class RpcServerApplication {
    public static void main(String[] args) throws Exception {
        String propertiesFile = args[0];
        if (args.length != 1) {
            System.out.println("请输入配置文件名称");
            return;
        }

        InputStream is = RpcServerApplication.class.getClassLoader().getResourceAsStream(propertiesFile);
        Properties properties = new Properties();
        properties.load(is);
        String address = properties.getProperty("server.address");
        String port = address.split(":")[1];
        String path = properties.getProperty("server.path");

        SpringApplication.run(RpcServerApplication.class, args);
        startServer(Integer.parseInt(port));

        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.1.142:2281")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("base")  // 独立的命名空间 /base
                .build();
        client.start();

        Stat stat = client.checkExists().forPath(path);
        if (stat != null) {
            client.delete().deletingChildrenIfNeeded().forPath(path);
            System.out.println("删除了上次的节点");
        }
        String s = client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL).forPath(path, address.getBytes());
        System.out.println("节点已经创建：" + s);

    }

    //创建一个方法启动服务器
    public static void startServer(int port) throws InterruptedException {
        //1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
//                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));

                        // 接收时的对象是 RpcRequest
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        // 回传时的对象是 String
                        pipeline.addLast(new StringEncoder());

//                        pipeline.addLast(new StringDecoder());

                        //把我们自定义的一个ChannelHandler添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(port).sync();
    }
}
